from . import api
from flask.helpers import make_response
import pika
from pika.channel import Channel
from ..tools.images.wordcloud import WordCloudGenerator
from ..tools.images.watermark import WaterMark
from ..tools.images.ocr import OCRModel
from . import api
from flask import json, request, jsonify
from app import connet_parameter
from app import redis_client
from uuid import uuid4
from app import executor


def send_asyn_rabbit(exchange, routing_key, body):
    # 初始化Rabbit生产者
    connection = pika.BlockingConnection(connet_parameter)
    channel: Channel = connection.channel()
    channel.basic_publish(exchange=exchange,
                          routing_key=routing_key,
                          body=json.dumps(body))
    channel.close()

# 进行pdf剪裁
@api.route('/document/pdfcut', methods=['POST'])
def pdfcut():
    data = request.json
    identifier = uuid4().hex
    data['identifier'] = identifier
    executor.submit(send_asyn_rabbit, 'pytools.system.direct', 'pdfcut',
                    data)
    return jsonify(identifier=identifier)

# 请求获取pdf
@api.route('/document/<uuid>', methods=['GET'])
def pdf_result(uuid):
    DOCUMENT_PREFIX = 'pytools:document:'
    result = redis_client.get(DOCUMENT_PREFIX + uuid)
    if result is None:
        return jsonify(status=1)
    return jsonify(status=0, document=result.decode('utf-8'))

# 添加pdf水印
@api.route('/document/pdfwatermark', methods=['POST'])
def pdf_watermaker():
    data = request.json
    identifier = uuid4().hex
    data['identifier'] = identifier
    executor.submit(send_asyn_rabbit, 'pytools.system.direct', 'pdfwatermarker',
                    data)
    return jsonify(identifier=identifier)

